<template>
  <el-dialog
    v-model="dialogVisible"
    title="远程升级"
    width="430"
    class="qc-custom-dialog"
  >
    <el-scrollbar>
      <div class="code-info">
        <el-form
          ref="updateRef"
          :model="ruleForm"
          :rules="rules"
          label-width="80px"
          class="edit-form-wrap"
        >
          <el-form-item label="电桩编码" class="bottom-wrap">
            <div>{{ ruleForm.equipmentCode }}</div>
          </el-form-item>
          <el-form-item label="升级版本" prop="updateVersion">
            <qc-select
              :value="ruleForm.updateVersion"
              :remote="true"
              :filterable="true"
              :options="optionsS.updateVersion"
              placeholder="请选择升级版本"
              @change="handleVersion"
            >
            </qc-select>
          </el-form-item>
        </el-form>
      </div>
    </el-scrollbar>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="hide">取消</el-button>
        <el-button type="primary" v-btnAntiShake="onSubmit"> 保存 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup name="dialog-price">
import { FormInstance, FormRules } from 'element-plus';
import { getChargingPileType, remoteUpdate } from '@/service/apis/pile';

let dialogVisible = ref(false);
const updateRef = ref<FormInstance>();

const optionsS = reactive({
  updateVersion: [] as any,
});

const ruleForm = reactive({
  id: '',
  equipmentCode: '',
  updateVersion: undefined as any,
});

const rules = reactive<FormRules>({
  updateVersion: [
    { required: true, message: '请选择升级版本', trigger: ['blur', 'change'] },
  ],
});

const handleVersion = (e: any) => {
  ruleForm.updateVersion = e;
};

const getVersion = (type: any) => {
  getChargingPileType({ chargingPileType: type }).then((res: any) => {
    optionsS.updateVersion = res || [];
  });
};

// 显示弹框
const show = (row: any) => {
  ruleForm.id = row.id;
  ruleForm.equipmentCode = row.equipmentCode;
  ruleForm.updateVersion = undefined as any;
  getVersion(row.type);
  dialogVisible.value = true;
};
// 关闭弹框
const hide = () => {
  dialogVisible.value = false;
};

const onSubmit = async () => {
  if (!updateRef.value) return;
  await updateRef.value.validate((valid: any, fields: any) => {
    if (valid) {
      const form = {
        id: ruleForm.id,
        equipmentCode: ruleForm.equipmentCode,
        updateVersion: ruleForm.updateVersion,
      };
      console.log('form---', form);
      remoteUpdate(form).then((res: any) => {
        ElMessage({
          showClose: true,
          message: '远程升级指令下发成功，请稍后查看电桩状态！',
          type: 'success',
        });
        hide();
      });
    } else {
      console.log('error submit!', fields);
    }
  });
};

defineExpose({
  show,
});
</script>

<style lang="scss" scoped>
.code-info {
  max-height: 50vh;
}
</style>